package com.example.mvpframe.provider.utils;

import android.util.Base64;

import java.nio.charset.StandardCharsets;
import java.util.Random;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class SHAHelper {

    public static final String KEY = "6CyPhdG8vgGppEw4GdKnsRMvEwq7RrbW8mxptjU";

    public static String getHMACSHA256(String data, String key) {
        try {
            Mac HmacSHA256 = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            HmacSHA256.init(secret_key);
            byte[] array = HmacSHA256.doFinal(data.getBytes(StandardCharsets.UTF_8));
            /*StringBuilder sb = new StringBuilder();
            for (byte item : array) {
                sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
            }*/
            return Base64.encodeToString(array, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    //length用户要求产生字符串的长度
    public static String getRandomString(int length) {
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(36);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }
}
